<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="serchForm" :model="form" :style="{ width: '100%' }">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input v-model="form.name" placeholder="请输入方案名称" allow-clear />
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="4">
                  <a-form-item field="state" hide-label>
                    <a-select v-model="form.close" placeholder="请选择方案状态" allow-clear>
                      <a-option value="0">正常</a-option>
                      <a-option value="1">关闭</a-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      style="width: 100%"
                      v-model="form.addTime"
                      show-time
                      placeholder="请选择开始创建时间"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      style="width: 100%"
                      v-model="form.endTime"
                      show-time
                      placeholder="请选择开始创建时间"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="getvortualList"
                        html-type="submit"
                        @click="doRefresh()"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button v-permission="getvortualList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button type="primary" v-permission="addVortual" @click="showAdd">
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>新建</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :loading="tableLoading"
          :bordered="{ wrapper: tables.bordered, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :data="table.dataList"
          :pagination="false"
          :row-key="rowKey"
          :row-class-name="rowClassNameFun"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
            >
              <template v-if="item.key === 'userRealName'" #cell="{ record }">
                <span v-if="record.userRealName">
                  <a-button style="padding: 0px 4px" type="text" size="small"> 已实名</a-button>
                </span>
                <span v-else>
                  <a-button style="padding: 0px 4px" type="text" size="small">未实名</a-button>
                </span>
              </template>
              <template v-else-if="item.key === 'setMeals'" #cell="{ record }">
                <span style="cursor: pointer" @click="seriesList(record.setMeals)">
                  {{ record.setMeals.length }}</span
                >
              </template>
              <!-- <template v-else-if="item.key === 'close'" #cell="{ record }">
                <a-switch v-model="record.close" @change="changeState(record)">
                  <template #checked-icon>
                    <icon-check />
                  </template>
                  <template #unchecked-icon>
                    <icon-close />
                  </template>
                </a-switch>
              </template> -->
              <template v-else-if="item.key === 'actions'" #cell="{ record }">
                <a-space :size="2">
                  <a-button
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    v-permission="updateVortual"
                    @click="updatUserPop(record)"
                    >编辑</a-button
                  >
                  <a-button
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    v-permission="addVortual"
                    @click="onCopy(record)"
                    >复制</a-button
                  >
                  <a-button
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    v-permission="delVortual"
                    @click="onDeleteItem(record)"
                    >删除</a-button
                  >
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableBody>
    <a-modal
      v-model:visible="visible"
      @before-close="handleCancel"
      title="添加方案"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="userForm" :auto-label-width="true" :model="subForm">
        <a-form-item
          label="方案名称"
          field="name"
          :rules="[
            { required: true, message: '方案名称不能为空' },
            { minLength: 1, maxLength: 100, message: '方案名称必须小于100个字符' },
          ]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input v-model.trim="subForm.name" placeholder="请输入方案名称" allow-clear />
        </a-form-item>
        <!-- <a-form-item field="close" label="方案状态">
          <a-radio-group v-model="subForm.close">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item> -->
        <a-form-item
          v-for="(post, index) of subForm.setMealFlowVirtualRules"
          :field="`posts.${index}.value`"
          :label="index == 0 ? '流量规则' : ''"
          :key="index"
        >
          <a-input-number
            v-model="post.usedFlow"
            :style="{ width: '320px' }"
            placeholder="请输入流量"
            hide-button
          >
            <template #append>
              <a-button
                type="primary"
                style="height: 20px"
                size="mini"
                @click="change1024(post.usedFlow, index)"
              >
                换算
              </a-button>
            </template>
          </a-input-number>

          <a-input-number
            v-model="post.proportion"
            :max="100"
            :style="{ width: '160px', marginLeft: '20px' }"
            placeholder="虚量比例"
            hide-button
          />
          <i-add
            style="cursor: pointer; margin-left: 10px"
            v-if="index == 0"
            size="18"
            @click="addItem"
          />
          <i-reduce
            style="cursor: pointer; margin-left: 10px"
            v-else
            size="18"
            @click="handleDelete(index)"
          />
        </a-form-item>
        <a-form-item label="模拟流量">
          <a-input-number v-model="xuliangForm.real" placeholder="请输入流量" hide-button>
            <template #append>
              <a-button
                type="primary"
                style="height: 20px"
                size="mini"
                @click="change1024s(xuliangForm.real)"
              >
                换算
              </a-button>
            </template>
          </a-input-number>
          <!-- <a-input-search
            placeholder="请输入流量"
            button-text="确定"
            allow-clear
            @search="clickSearch"
            search-button
          /> -->
          <a-button type="primary" @click="clickSearch"> 确认 </a-button>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleBeforeOk">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <a-modal
      v-model:visible="addtagvisibles"
      title="应用系列"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <Table :tablist="series" />
      <template #footer>
        <a-space />
      </template>
    </a-modal>
    <a-modal
      v-model:visible="jiancevisible"
      @before-close="jiancevisible = false"
      title="模拟流量"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-tag bordered color="#FFF7E8" size="medium" style="width: 100%; height: 36px">
        <p
          style="
            text-align: center;
            color: #000;
            font-size: 14px;
            width: 100%;
            text-align: center;
            padding: 6px;
            box-sizing: border-box;
          "
          >当前真实使用流量：<span style="color: #3491fa"
            >{{ (xuliangForm.real / 1024).toFixed(2) }}G</span
          >，当前虚量比例：<span style="color: #3491fa">{{ xuliangForm.imaginary }}%</span
          >，虚量后显示流量：<span style="color: #3491fa"
            >{{ (xuliangForm.nowbl / 1024).toFixed(2) }}G</span
          ></p
        ></a-tag
      >
      <a-tag color="red" size="medium" style="width: 100%; height: 36px; margin-top: 20px">
        <p
          style="
            text-align: center;
            font-size: 14px;
            width: 100%;
            text-align: center;
            padding: 6px;
            box-sizing: border-box;
          "
        >
          流量计算公式：真实流量 ÷ (1 - 虚量%) 简单公式：10 ÷ 0.5
        </p>
      </a-tag>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import useCommonStore from '@/store/modules/common'
  import * as http from '@/api/http'
  import Table from '@/views/polling/compoents/table.vue'
  import { getvortualList, addVortual, exportVortual, updateVortual, delVortual } from '@/api/url'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { onMounted, reactive, ref } from 'vue'
  const useCommon = useCommonStore()
  const table = useTable()
  const pagination = usePagination(doRefresh)
  const rowKey = useRowKey('id')
  const visible = ref(false)
  const jiancevisible = ref(false)
  const addtagvisibles = ref(false)
  const btnLoading = ref(false)
  const userForm = ref<typeof Form>()
  const form = reactive({
    name: '',
    addTime: '',
    endTime: '',
  })
  const series = ref([])
  const subForm: any = ref({
    name: '',
    setMealFlowVirtualRules: [
      {
        usedFlow: '', //赠送金额
        proportion: '', //是否推荐 true推荐, false不推荐
      },
    ], //预存金额充值列表
    close: true,
  })
  const tableColumns: any = reactive({
    list: [
      {
        title: '方案名称',
        key: 'name',
        dataIndex: 'name',
        checked: true,
        width: 220,
      },
      {
        title: '应用系列',
        key: 'setMeals',
        dataIndex: 'setMeals',
        checked: true,
        width: 220,
      },
      // {
      //   title: '方案状态',
      //   key: 'close',
      //   dataIndex: 'close',
      //   checked: true,
      // },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'actions',
        fixed: 'right',
        dataIndex: 'actions',
        width: 180,
        align: 'center',
        checked: true,
      },
    ],
  })
  const tableLoading = ref(false)
  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })
  function seriesList(val: any) {
    series.value = val
    addtagvisibles.value = true
  }
  function showAdd() {
    subForm.value = {
      name: '',
      setMealFlowVirtualRules: [
        {
          usedFlow: '', //赠送金额
          proportion: '', //是否推荐 true推荐, false不推荐
        },
      ], //预存金额充值列表
      close: true,
    }
    visible.value = true
  }
  const addItem = () => {
    // if (subForm.value.setMealFlowVirtualRules.length >= 6) {
    //   Message.error('已达最大限制6条')
    //   return false
    // }
    subForm.value.setMealFlowVirtualRules.push({
      usedFlow: '', //赠送金额
      proportion: '', //是否推荐 true推荐, false不推荐
    })
  }
  const handleDelete = (index: any) => {
    subForm.value.setMealFlowVirtualRules.splice(index, 1)
  }

  function handleCancel() {
    userForm.value?.resetFields()
    visible.value = false
  }

  const change1024 = (item: any, value: any) => {
    subForm.value.setMealFlowVirtualRules[value].usedFlow = item * 1024
  }

  const change1024s = (item: any) => {
    xuliangForm.real = item * 1024
  }

  const serchForm = ref()
  const resetSeach = () => {
    serchForm.value.resetFields()
    doRefresh(1)
  }
  function updatUserPop(item: any) {
    subForm.value = JSON.parse(JSON.stringify(item))
    visible.value = true
  }
  function onDeleteItem(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此方案吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        http
          .get({
            url: delVortual,
            data: () => {
              return {
                id: item.id,
              }
            },
          })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              doRefresh()
            } else {
              Message.error(res.msg)
            }
          })
          .catch(console.log)
      },
    })
  }
  const xuliangForm: any = reactive({
    real: '',
    imaginary: '',
    nowbl: '',
  })
  function clickSearch(item: any) {
    console.log(item)
    if (xuliangForm.real == '') {
      Message.error('流量输入不能为空！')
      return false
    }
    if (xuliangForm.real <= 0) {
      Message.error('流量输入不能小于等于0！')
      return false
    }
    subForm.value.setMealFlowVirtualRules.forEach((el: any) => {
      if (el.usedFlow != '') {
        if (Number(item) <= el.usedFlow) {
          console.log(el, Number(item), 100 - Number(el.proportion))
          xuliangForm.nowbl = (Number(item) / (1 - Number(el.proportion) / 100)).toFixed(2)
          xuliangForm.imaginary = el.proportion
          console.log(xuliangForm)
          jiancevisible.value = true
          throw Error()
        }
      } else {
        Message.error('请检查阈值输入是否为空！')
      }
    })
  }
  function onCopy(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要复制方案吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        http
          .post({
            url: addVortual,
            data: () => {
              return {
                ...item,
              }
            },
          })
          .then((res) => {
            btnLoading.value = false
            if (res.code == 0) {
              Message.success('复制成功')
              visible.value = false
              userForm.value?.resetFields()
              doRefresh()
            } else {
              Message.error(res.msg)
            }
          })
      },
    })
  }
  function handleBeforeOk() {
    console.log(subForm)
    userForm.value?.validate().then((error: any) => {
      if (!error) {
        if (!subForm.value.id) {
          http
            .post({
              url: addVortual,
              data: () => {
                return {
                  ...subForm.value,
                }
              },
            })
            .then((res) => {
              btnLoading.value = false
              if (res.code == 0) {
                Message.success(res.msg)
                visible.value = false
                subForm.value.id = null
                userForm.value?.resetFields()
                doRefresh()
              } else {
                Message.error(res.msg)
              }
            })
        } else {
          http
            .post({
              url: updateVortual,
              data: () => {
                return {
                  ...subForm.value,
                }
              },
            })
            .then((res) => {
              btnLoading.value = false
              if (res.code == 0) {
                Message.success(res.msg)
                visible.value = false
                subForm.value.id = null
                userForm.value?.resetFields()
                doRefresh()
              } else {
                Message.error(res.msg)
              }
            })
        }
      }
    })
  }
  // function changeState(item: any) {
  //   console.log(item)
  //   http
  //     .get({
  //       url: setRecharge,
  //       data: () => {
  //         return {
  //           close: item.close,
  //           id: item.id,
  //         }
  //       },
  //     })
  //     .then((res) => {
  //       if (res.code == 0) {
  //         Message.success(res.msg)
  //         doRefresh()
  //       } else {
  //         Message.error(res.msg)
  //       }
  //     })
  // }
  function doRefresh(value?: number) {
    // eslint-disable-next-line prettier/prettier
    tableLoading.value = true
    if (value) {
    }
    http
      .get({
        url: getvortualList,
        data: () => {
          return {
            ...form,
          }
        },
      })
      .then((res) => {
        tableLoading.value = false
        table.handleSuccess(res.data)
      })
      .catch(console.log)
  }

  const onUpdateBorder = (isBordered: boolean) => {
    tables.bordered = isBordered
  }
  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }
  function rowClassNameFun(_record: any, index: number) {
    return index % 2 === 1 && table.striped.value ? 'table-striped' : null
  }
  onMounted(async () => {
    doRefresh()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-input-append) {
    border: 0;
  }
  :deep(.arco-btn-size-mini) {
    padding: 0 7px;
  }
  .top {
    margin-bottom: 20px;
    background-color: var(--color-bg-1);
    border-radius: 10px;

    .box {
      display: flex;
      align-items: center;
      height: 30px;
      margin: 5px 10px;

      .line {
        width: 5px;
        height: 25px;
        margin-right: 10px;
        background-color: #40a1ff;
      }

      .text {
        font-size: 16px;
        line-height: 25px;
        text-align: center;
      }
    }

    .flex {
      display: flex;
      justify-content: space-around;
      margin: 12px 7px;
      .dataBox:last-child {
        margin-right: 0px !important;
      }
      .dataBox {
        display: flex;
        align-items: center;
        justify-content: center;
        align-items: center;
        flex: 1;
        margin-right: 20px;
        height: 150px;
        background-image: linear-gradient(rgb(var(--arcoblue-1)), #fff);
        border: 1px solid #f2f3f5;
        border-radius: 10px;

        .img {
          width: 70px;
          height: 70px;
          margin-right: 20px;
          border-radius: 50%;
        }

        .name {
          margin-top: 0;
        }

        .number {
          font-size: 22px;
        }
      }
    }
  }
  .avatar-container {
    position: relative;
    width: 30px;
    height: 30px;
    margin: 0 auto;
    vertical-align: middle;
    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
    .avatar-vip {
      border: 2px solid #cece1e;
    }
    .vip {
      position: absolute;
      top: 0;
      right: -9px;
      width: 15px;
      transform: rotate(60deg);
    }
  }
  .gender-container {
    .gender-icon {
      width: 20px;
    }
  }
  .custom-checkbox-card {
    padding: 5px 16px;
    border-radius: 4px;
    width: auto;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    background-color: var(--color-fill-2);
  }

  .custom-checkbox-card-mask {
    height: 14px;
    width: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 2px;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
  .custom-checkbox-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 2px;
  }

  .custom-checkbox-card-title {
    color: var(--color-text-1);
    font-size: 14px;
  }

  .custom-checkbox-card:hover,
  .custom-checkbox-card-checked,
  .custom-checkbox-card:hover .custom-checkbox-card-mask,
  .custom-checkbox-card-checked .custom-checkbox-card-mask {
    border-color: rgb(var(--primary-6));
  }

  .custom-checkbox-card:hover .custom-checkbox-card-title,
  .custom-checkbox-card-checked .custom-checkbox-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }
</style>
<style scoped>
  .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }
</style>
